﻿using AzukiMap.Map;
using AzukiMap.MapSource;
using AzukiMap.Renderer;
using AzukiMap.Request;
using Geotools.Geometries;
using System.Xml.Linq;
using System.Collections.Generic;

namespace AzukiMap.Layer
{
    public class RasterIndexLayer : Layer
    {
        RasterRenderer _renderer;
        List<RasterIndexRecord> _records;
        List<int> _renderedImages;
        bool _isClockWise = true;

        public bool IsClockWise
        {
            get { return _isClockWise; }
            set { _isClockWise = value; }
        }

        public RasterIndexLayer(MapCanvas mapCanvas, string name)
            : base(mapCanvas, MapSourceTypes.Raster, new RasterFileSource())
        {
            _renderer = new RasterRenderer(mapCanvas);
            _records = new List<RasterIndexRecord>();
            _renderedImages = new List<int>();
            _name = name;
        }

        public override void Draw()
        {
            if (_isRendering)
            {
                return;
            }
            if (!_isVisible)
            {
                return;
            }
            if (!CheckScale())
            {
                return;
            }
            _isRendering = true;
            DrawInExtent();
        }

        public void AddRaster(RasterIndexRecord record)
        {
            _records.Add(record);
        }

        public void RemoveRaster(RasterIndexRecord record)
        {
            _records.Remove(record);
        }

        public void RemoveRasterAll()
        {
            _records.Clear();
        }

        void DrawInExtent()
        {
            // TODO: get uniq ID from records.
            int id = 0;
            foreach (RasterIndexRecord record in _records)
            {
                if (!_renderedImages.Contains(record.id))
                {
                    if (IsOnMapCanvas(record.Extent)) {
                        _renderer.DrawRaster(id, record.Extent, record.RasterIndex, _isClockWise);
                    }
                }
            }
            _isRendering = false;
        }

        public override XElement ToXml()
        {
            return ToXml("RasterIndexLayer");
        }

        public override XElement ToXml(string elementName)
        {
            XElement vectorLayerXml = base.ToXml(elementName);
            return vectorLayerXml;
        }

        protected bool IsOnMapCanvas(GTPolygon extent)
        {
            bool isInCanvas = (_mapCanvas.CurrentExtent.Intersects(extent));
            bool isInMaxExtent = true;
            if ( _maxExtent != null)
                isInMaxExtent = (_maxExtent.Intersects(extent));
            return (isInCanvas && isInMaxExtent);
        }
    }
}
